package com.cbd.rabbitmq;

import com.cbd.entity.OpLogEntity;
import com.cbd.mapper.OpLogMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author BingBing
 * @desc RabbitMQ消费者类
 * @date 2024/11/14 14:33
 */
@Component
@Slf4j
public class MyMQConsumer {

    @Resource
    OpLogMapper opLogMapper;

    @RabbitListener(queues = "opQueue", ackMode = "MANUAL")  // 监听队列名为opQueue的队列
    public void receiveMessage(Channel channel, Message message) {
        // 手动确认消息
        try {
            log.info("Received message1:{} ", message);
            // 将消息转换为OpLogEntity对象
            OpLogEntity opLogEntity = new OpLogEntity();
            // 反序列化
            ObjectMapper objectMapper = new ObjectMapper();
            opLogEntity = objectMapper.readValue(message.getBody(), OpLogEntity.class);
            opLogMapper.insert(opLogEntity);
            // 参数1：deliveryTag，消息的序号，消息的唯一标识，在消费者中被标记为已确认
            // 参数2：multiple，是否批量确认，false表示单条确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }  catch (Exception e) {
            log.error("消息确认失败：{}", e.getMessage());
        }
    }
}
